package com.bw.services.IM

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.text.TextUtils
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bw.services.R
import com.hyphenate.EMMessageListener
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMMessage
import com.hyphenate.chat.EMTextMessageBody
import com.hyphenate.chat.EMImageMessageBody
import com.hyphenate.exceptions.HyphenateException
import java.util.*
import android.database.Cursor

class IMChatActivity : AppCompatActivity() {
    private lateinit var tvTitle: TextView
    private lateinit var rvMessages: RecyclerView
    private lateinit var etInput: EditText
    private lateinit var btnSend: View
    private lateinit var btnSendImage: ImageView
    private lateinit var adapter: MessageListAdapter
    private val messages = mutableListOf<ChatMessage>()
    private var toUsername: String = ""
    private var toNickname: String = ""
    private val REQUEST_IMAGE_PICK = 1001

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_imchat)
        tvTitle = findViewById(R.id.tv_title)
        rvMessages = findViewById(R.id.rv_messages)
        etInput = findViewById(R.id.et_input)
        btnSend = findViewById(R.id.btn_send)
        btnSendImage = findViewById(R.id.btn_send_image)

        toUsername = intent.getStringExtra("username") ?: ""
        toNickname = intent.getStringExtra("nickname") ?: toUsername
        tvTitle.text = toNickname

        adapter = MessageListAdapter(messages, EMClient.getInstance().currentUser)
        rvMessages.layoutManager = LinearLayoutManager(this)
        rvMessages.adapter = adapter

        btnSend.setOnClickListener {
            val content = etInput.text.toString().trim()
            if (content.isNotEmpty()) {
                sendTextMessage(content)
                etInput.setText("")
            }
        }
        btnSendImage.setOnClickListener {
            pickImageFromGallery()
        }
        loadMessages()
        EMClient.getInstance().chatManager().addMessageListener(messageListener)
    }

    override fun onDestroy() {
        super.onDestroy()
        EMClient.getInstance().chatManager().removeMessageListener(messageListener)
    }

    private fun loadMessages() {
        val conversation = EMClient.getInstance().chatManager().getConversation(toUsername)
        if (conversation == null) {
            messages.clear()
            adapter.notifyDataSetChanged()
            return
        }
        // 新增：获取所有历史消息
        val allMessages = mutableListOf<EMMessage>()
        val pageSize = 50 // 每次加载50条
        var msgList = conversation.allMessages
        if (msgList.isNotEmpty()) {
            var earliestMsgId = msgList.first().msgId
            while (true) {
                val more = conversation.loadMoreMsgFromDB(earliestMsgId, pageSize)
                if (more.isNullOrEmpty()) break
                allMessages.addAll(0, more)
                earliestMsgId = more.first().msgId
            }
        }
        allMessages.addAll(msgList)
        messages.clear()
        allMessages.forEach { emMsg ->
            messages.add(ChatMessage.fromEMMessage(emMsg, EMClient.getInstance().currentUser))
        }
        adapter.notifyDataSetChanged()
        rvMessages.scrollToPosition(messages.size - 1)
    }

    private fun sendTextMessage(content: String) {
        val message = EMMessage.createTxtSendMessage(content, toUsername)
        EMClient.getInstance().chatManager().sendMessage(message)
        messages.add(ChatMessage(content, null, true, ChatMessage.Type.TEXT))
        adapter.notifyItemInserted(messages.size - 1)
        rvMessages.scrollToPosition(messages.size - 1)
    }

    private fun sendImageMessage(imageUri: Uri) {
        // 新增：将 content uri 转为真实文件路径
        val filePath = getRealPathFromUri(imageUri)
        if (filePath == null) {
            Toast.makeText(this, "图片路径获取失败", Toast.LENGTH_SHORT).show()
            return
        }
        val message = EMMessage.createImageSendMessage(filePath, false, toUsername)
        EMClient.getInstance().chatManager().sendMessage(message)
        messages.add(ChatMessage(null, imageUri.toString(), true, ChatMessage.Type.IMAGE))
        adapter.notifyItemInserted(messages.size - 1)
        rvMessages.scrollToPosition(messages.size - 1)
    }

    private fun pickImageFromGallery() {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        startActivityForResult(intent, REQUEST_IMAGE_PICK)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_IMAGE_PICK && resultCode == Activity.RESULT_OK) {
            val uri = data?.data
            if (uri != null) {
                sendImageMessage(uri)
            }
        }
    }

    private val messageListener = object : EMMessageListener {
        override fun onMessageReceived(messagesList: MutableList<EMMessage>?) {
            runOnUiThread {
                messagesList?.forEach { emMsg ->
                    if (emMsg.from == toUsername) {
                        messages.add(ChatMessage.fromEMMessage(emMsg, EMClient.getInstance().currentUser))
                        adapter.notifyItemInserted(messages.size - 1)
                        rvMessages.scrollToPosition(messages.size - 1)
                    }
                }
            }
        }
        override fun onCmdMessageReceived(messages: MutableList<EMMessage>?) {}
        override fun onMessageRead(messages: MutableList<EMMessage>?) {}
        override fun onMessageDelivered(messages: MutableList<EMMessage>?) {}
        override fun onMessageRecalled(messages: MutableList<EMMessage>?) {}
        override fun onMessageChanged(message: EMMessage?, change: Any?) {}
    }

    // 新增：uri转文件路径方法（放在类内部，使用this.contentResolver）
    private fun getRealPathFromUri(uri: Uri): String? {
        var path: String? = null
        val projection = arrayOf(MediaStore.Images.Media.DATA)
        val cursor: Cursor? = this.contentResolver.query(uri, projection, null, null, null)
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                val columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
                path = cursor.getString(columnIndex)
            }
            cursor.close()
        }
        return path
    }
}

// 消息数据类
class ChatMessage(
    val text: String?,
    val imageUrl: String?,
    val isSelf: Boolean,
    val type: Type
) {
    enum class Type { TEXT, IMAGE }
    companion object {
        fun fromEMMessage(msg: EMMessage, selfUsername: String): ChatMessage {
            return when (msg.type) {
                EMMessage.Type.TXT -> ChatMessage((msg.body as EMTextMessageBody).message, null, msg.from == selfUsername, Type.TEXT)
                EMMessage.Type.IMAGE -> {
                    val body = msg.body as EMImageMessageBody
                    val isSelf = msg.from == selfUsername
                    val imageUrl = if (isSelf) body.localUrl else body.remoteUrl
                    ChatMessage(null, imageUrl, isSelf, Type.IMAGE)
                }
                else -> ChatMessage("[不支持的消息类型]", null, msg.from == selfUsername, Type.TEXT)
            }
        }
    }
} 